<!-- 现代化聊天界面 -->
<template>
  <view class="chat-container">
    <!-- 聊天头部 -->
    <view class="chat-header">
      <view class="header-left">
        <image :src="friendAvatar" class="header-avatar" mode="aspectFill"></image>
        <view class="header-info">
          <text class="friend-name">{{ friendName }}</text>
          <text class="online-status" :class="{ online: isOnline }">
            {{ isOnline ? '在线' : '离线' }}
          </text>
        </view>
      </view>
      <view class="header-right">
        <tui-icon name="more" size="20" color="#666" @click="showMoreOptions"></tui-icon>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-into-view="lastMessageAnchor"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
      @scroll="onScroll"
      @tap="focusInput"
      :lower-threshold="50"
      :upper-threshold="50"
    >
      <view class="message-container">
        <!-- 加载更多提示 -->
        <view class="load-more" v-if="loading">
          <tui-loading size="20" color="#999"></tui-loading>
          <text class="load-text">加载中...</text>
        </view>

        <!-- 消息项 -->
        <view 
          class="message-item" 
          :class="[item.userType, { 'show-time': item.showTime }]" 
          v-for="(item, index) in messageList" 
          :key="item.id || index"
          :id="'msg-' + (item.id || index)"
        >
          <!-- 时间显示 -->
          <view class="message-time" v-if="item.showTime">
            {{ formatTime(item.createTime) }}
          </view>

          <!-- 消息内容 -->
          <view class="message-content" :class="item.userType">
            <!-- 对方头像 -->
            <image 
              v-if="item.userType === 'friend' && item.avatar" 
              :src="item.avatar" 
              class="message-avatar" 
              mode="aspectFill"
            ></image>
            <view v-else-if="item.userType === 'friend'" class="message-avatar text-avatar">客</view>

            <!-- 消息气泡 -->
            <view class="message-bubble" :class="item.userType" @longpress="onMessageAction(item)">
              <text class="message-text">{{ item.content }}</text>
            </view>

            <!-- 自己头像 -->
            <image 
              v-if="item.userType === 'self' && item.avatar" 
              :src="item.avatar" 
              class="message-avatar" 
              mode="aspectFill"
            ></image>
            <view v-else-if="item.userType === 'self'" class="message-avatar text-avatar">我</view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="messageList.length === 0 && !loading">
          <view class="empty-icon">💬</view>
          <text class="empty-text">开始聊天吧~</text>
        </view>
      </view>
    </scroll-view>

    <!-- 新消息提示 -->
    <view v-if="showNewMsgTip" class="new-msg-tip" @click="scrollToBottom()">
      <text>有{{ unreadCount }}条新消息</text>
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-container">
        <view class="emoji-btn" :class="{ 'active': showEmojiPanel }" @click="toggleEmojiPanel">
          <text class="emoji-icon">😊</text>
        </view>
        <input 
          v-model="inputText" 
          class="message-input" 
          placeholder="输入消息..." 
          :focus="inputFocus"
          confirm-type="send"
          @confirm="sendMessage"
          @focus="onInputFocus"
          @blur="onInputBlur"
        />
        <view 
          class="send-btn" 
          :class="{ 'active': inputText.trim() && !sendingInProgress }" 
          @tap="sendMessage"
        >
          <tui-icon name="send" size="20" color="#fff"></tui-icon>
        </view>
      </view>
      
      <!-- 表情面板 -->
      <view class="emoji-panel" v-show="showEmojiPanel" :class="{ 'show': showEmojiPanel }">
        <view class="emoji-header">
          <text class="emoji-title">选择表情</text>
          <view class="emoji-close" @click="closeEmojiPanel">
            <tui-icon name="shut" size="20" color="#666"></tui-icon>
          </view>
        </view>
        <scroll-view class="emoji-list" scroll-y>
          <view class="emoji-grid">
            <view 
              class="emoji-item" 
              v-for="(emoji, index) in emojiList" 
              :key="index"
              @click="selectEmoji(emoji)"
            >
              {{ emoji }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import tuiButton from '@/components/thorui/tui-button/tui-button.vue'
import tuiIcon from '@/components/thorui/tui-icon/tui-icon.vue'
import tuiLoading from '@/components/thorui/tui-loading/tui-loading.vue'

export default {
  components: {
    tuiButton,
    tuiIcon,
    tuiLoading
  },
  data() {
    return {
      // 页面参数
      friendName: '在线客服',
      friendAvatar: '/static/img/tabs/my.png',
      chatType: 'refund', // 聊天类型：refund, general
      orderNo: '',
      refundNo: '',
      
      // 消息相关
      messageList: [],
      inputText: '',
      inputFocus: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      hasMore: true,
      
      // 滚动相关
      scrollTop: 0,
      isOnline: true,
      lastMessageAnchor: '',
      lastSendAt: 0,
      isAtBottom: true,
      showNewMsgTip: false,
      unreadCount: 0,
      sendingInProgress: false,
      
      // WebSocket相关
      socketTask: null,
      reconnectTimer: null,
      reconnectCount: 0,
      maxReconnectCount: 5,
      
      
      // 用户信息
      userInfo: {},
      token: '',
      preset: '',
      
      // 表情相关
      showEmojiPanel: false,
      emojiList: [
        '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
        '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
        '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
        '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
        '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬',
        '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗',
        '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯',
        '😦', '😧', '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐',
        '🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕', '🤑', '🤠', '😈',
        '👿', '👹', '👺', '🤡', '💩', '👻', '💀', '☠️', '👽', '👾',
        '🤖', '🎃', '😺', '😸', '😹', '😻', '😼', '😽', '🙀', '😿',
        '😾', '👶', '🧒', '👦', '👧', '🧑', '👨', '👩', '🧓', '👴',
        '👵', '👤', '👥', '👪', '🤳', '💪', '🦾', '🦿', '🦵', '🦶',
        '👂', '🦻', '👃', '🧠', '🦷', '🦴', '👀', '👁️', '👅', '👄',
        '💋', '🩸', '💔', '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤',
        '🤍', '🤎', '💯', '💢', '💥', '💫', '💦', '💨', '🕳️', '💣',
        '💤', '🔥', '⭐', '🌟', '💫', '✨', '⚡', '☀️', '🌙', '🌚',
        '🌝', '🌛', '🌜', '🌕', '🌖', '🌗', '🌘', '🌑', '🌒', '🌓',
        '🌔', '🌍', '🌎', '🌏', '🌋', '🌌', '🌊', '⛰️', '🏔️', '🗻',
        '🏕️', '🏖️', '🏜️', '🏝️', '🏞️', '🏟️', '🏛️', '🏗️', '🧱', '🏘️',
        '🏚️', '🏠', '🏡', '🏢', '🏣', '🏤', '🏥', '🏦', '🏧', '🏨',
        '🏩', '🏪', '🏫', '🏬', '🏭', '🏮', '🏯', '🏰', '💒', '🗼',
        '🗽', '⛪', '🕌', '🛕', '🕍', '⛩️', '🕋', '⛲', '⛺', '🌉',
        '🌁', '🚁', '🚂', '🚃', '🚄', '🚅', '🚆', '🚇', '🚈', '🚉',
        '🚊', '🚝', '🚞', '🚋', '🚌', '🚍', '🚎', '🚐', '🚑', '🚒',
        '🚓', '🚔', '🚕', '🚖', '🚗', '🚘', '🚙', '🚚', '🚛', '🚜',
        '🏎️', '🏍️', '🛵', '🛺', '🚲', '🛴', '🛹', '🛼', '🛷', '⛸️',
        '🥌', '🎿', '🛷', '🛸', '🚀', '🛰️', '💺', '🛩️', '✈️', '🛫',
        '🛬', '🪂', '💺', '🚁', '🚟', '🚠', '🚡', '⛴️', '🛥️', '🚤',
        '⛵', '🛶', '🚣', '🏊', '🏄', '🏇', '🧘', '🏃', '🚶', '🧑‍🤝‍🧑',
        '👫', '👬', '👭', '💑', '👩‍❤️‍👩', '👨‍❤️‍👨', '💏', '👩‍❤️‍💋‍👩', '👨‍❤️‍💋‍👨', '👪',
        '👨‍👩‍👧', '👨‍👩‍👧‍👦', '👨‍👩‍👦‍👦', '👨‍👩‍👧‍👧', '👨‍👨‍👦', '👨‍👨‍👧', '👨‍👨‍👧‍👦', '👨‍👨‍👦‍👦', '👨‍👨‍👧‍👧', '👩‍👩‍👦',
        '👩‍👩‍👧', '👩‍👩‍👧‍👦', '👩‍👩‍👦‍👦', '👩‍👩‍👧‍👧', '👨‍👦', '👨‍👦‍👦', '👨‍👧', '👨‍👧‍👦', '👨‍👧‍👧', '👩‍👦',
        '👩‍👦‍👦', '👩‍👧', '👩‍👧‍👦', '👩‍👧‍👧', '🗣️', '👤', '👥', '👣', '🐵', '🐒',
        '🦍', '🦧', '🐶', '🐕', '🦮', '🐕‍🦺', '🐩', '🐺', '🦊', '🦝',
        '🐱', '🐈', '🦁', '🐯', '🐅', '🐆', '🐴', '🐎', '🦄', '🦓',
        '🦌', '🐮', '🐂', '🐃', '🐄', '🐷', '🐖', '🐗', '🐽', '🐑',
        '🐐', '🐪', '🐫', '🦙', '🦒', '🐘', '🦏', '🦛', '🐭', '🐁',
        '🐀', '🐹', '🐰', '🐇', '🐿️', '🦔', '🦇', '🐻', '🐨', '🐼',
        '🦥', '🦦', '🦨', '🦘', '🦡', '🐾', '🦃', '🐔', '🐓', '🐣',
        '🐤', '🐥', '🐦', '🐧', '🕊️', '🦅', '🦆', '🦢', '🦉', '🦩',
        '🦚', '🦜', '🐸', '🐊', '🐢', '🦎', '🐍', '🐲', '🐉', '🦕',
        '🦖', '🐳', '🐋', '🐬', '🐟', '🐠', '🐡', '🦈', '🐙', '🐚',
        '🐌', '🐛', '🐜', '🐝', '🐞', '🦗', '🕷️', '🕸️', '🦂', '🦟',
        '🦠', '💐', '🌸', '💮', '🏵️', '🌹', '🥀', '🌺', '🌻', '🌼',
        '🌷', '🌱', '🌲', '🌳', '🌴', '🌵', '🌶️', '🌷', '🌸', '🌹',
        '🌺', '🌻', '🌼', '🌽', '🌾', '🌿', '🍀', '🍁', '🍂', '🍃',
        '🍇', '🍈', '🍉', '🍊', '🍋', '🍌', '🍍', '🥭', '🍎', '🍏',
        '🍐', '🍑', '🍒', '🍓', '🫐', '🥝', '🍅', '🫒', '🥥', '🥑',
        '🍆', '🥔', '🥕', '🌽', '🌶️', '🫑', '🥒', '🥬', '🥦', '🧄',
        '🧅', '🍄', '🥜', '🌰', '🍞', '🥐', '🥖', '🫓', '🥨', '🥯',
        '🥞', '🧇', '🧀', '🍖', '🍗', '🥩', '🥓', '🍔', '🍟', '🍕',
        '🌭', '🥪', '🌮', '🌯', '🫔', '🥙', '🧆', '🥚', '🍳', '🥘',
        '🍲', '🫕', '🥣', '🥗', '🍿', '🧈', '🧂', '🥫', '🍱', '🍘',
        '🍙', '🍚', '🍛', '🍜', '🍝', '🍠', '🍢', '🍣', '🍤', '🍥',
        '🥮', '🍡', '🥟', '🥠', '🥡', '🦀', '🦞', '🦐', '🦑', '🦪',
        '🍦', '🍧', '🍨', '🍩', '🍪', '🎂', '🍰', '🧁', '🥧', '🍫',
        '🍬', '🍭', '🍮', '🍯', '🍼', '🥛', '☕', '🫖', '🍵', '🍶',
        '🍾', '🍷', '🍸', '🍹', '🍺', '🍻', '🥂', '🥃', '🥤', '🧋',
        '🧃', '🧉', '🧊', '🥢', '🍽️', '🍴', '🥄', '🔪', '🏺'
      ]
    };
  },
  onLoad(options) {
    // 获取页面参数
    this.friendName = decodeURIComponent(options.userName || '') || '在线客服';
    this.friendAvatar = decodeURIComponent(options.userAvatar || '') || '/static/img/tabs/my.png';
    this.chatType = options.type || 'general';
    this.orderNo = options.orderNo || '';
    this.refundNo = options.refundNo || '';
    
    // 预置首条消息
    if (options.preset) {
      try { 
        this.preset = decodeURIComponent(options.preset); 
      } catch(e) { 
        this.preset = options.preset; 
      }
    }
    
    uni.setNavigationBarTitle({ title: this.friendName });
    
    // 获取用户信息和 token
    this.userInfo = uni.getStorageSync('userInfo') || {};
    this.token = uni.getStorageSync('userToken') || '';
    
    // 初始化聊天
    this.initChat();
  },
  
  onShow() {
    uni.setNavigationBarTitle({ title: this.friendName || '在线客服' });
    setTimeout(() => {
      this.inputFocus = true;
    }, 500);
    
    if (this.token) {
      this.connectWebSocket();
    }
  },
  
  onHide() {
    this.closeWebSocket();
  },
  
  onUnload() {
    this.closeWebSocket();
  },
  
  methods: {
    // 初始化聊天
    initChat() {
      // 先加载历史消息
      this.loadMessageList();
      
      // 根据 token 决定实时通道：优先 WebSocket，失败自动降级轮询
      try {
        this.userInfo = uni.getStorageSync('userInfo') || this.userInfo || {};
        this.token = uni.getStorageSync('userToken') || this.token || '';
      } catch (e) {}
      
      if (this.token) {
        this.connectWebSocket();
      } else {
        this.startMessagePolling();
      }
    },
    
    // 连接 WebSocket
    connectWebSocket() {
      try {
        if (this.socketTask && this.isOnline) return;
        const wsUrl = `wss://www.liujianggongyi.site/app-api/infra/ws?token=${this.token}`;
        console.log('尝试连接WebSocket:', wsUrl);
        
        this.socketTask = uni.connectSocket({
          url: wsUrl,
          success: () => {
            console.log('WebSocket连接请求已发送');
          },
          fail: (err) => {
            console.error('WebSocket连接失败:', err);
            this.handleWebSocketError();
          }
        });

        this.socketTask.onOpen(async () => {
          console.log('WebSocket连接成功');
          this.reconnectCount = 0;
          this.isOnline = true;
          
          // 连接成功后发送预置消息
          if (this.preset) {
            try {
              await this.$api.req('/promotion/kefu-message/send', {
                contentType: 1,
                content: this.preset
              }, 'POST', 'JSON', false);
              this.preset = '';
              this.refreshMessageList();
            } catch (e) {}
          }
        });

        this.socketTask.onMessage((res) => {
          console.log('收到WebSocket消息:', res);
          this.handleWebSocketMessage(res.data);
        });

        this.socketTask.onError((err) => {
          console.error('WebSocket错误:', err);
          this.handleWebSocketError();
        });

        this.socketTask.onClose(() => {
          console.log('WebSocket连接关闭');
          this.isOnline = false;
          this.autoReconnect();
        });

      } catch (error) {
        console.error('WebSocket连接异常:', error);
        this.handleWebSocketError();
      }
    },
    
    // 处理WebSocket消息
    handleWebSocketMessage(data) {
      try {
        const payload = JSON.parse(data);
        if (payload && payload.type === 'KEFU_MESSAGE_TYPE') {
          const content = payload.content ? JSON.parse(payload.content) : {};
          
          this.addMessage({
            id: content.id || Date.now(),
            content: this.parseContent(content.content || content.text),
            userType: content.senderType === 1 ? 'self' : 'friend',
            avatar: content.senderType === 1 ? (this.userInfo.avatar || '/static/img/tabs/my.png') : this.friendAvatar,
            createTime: content.createTime || Date.now(),
            showTime: (this.messageList.length === 0) ? true : this.shouldShowTime(content.createTime || Date.now(), this.messageList[this.messageList.length - 1].createTime)
          });
        }
      } catch (error) {
        console.error('解析WebSocket消息失败:', error);
      }
    },
    
    // 处理WebSocket错误
    handleWebSocketError() {
      this.isOnline = false;
    },

    // 自动重连
    autoReconnect() {
      if (this.reconnectCount < this.maxReconnectCount) {
        this.reconnectCount++;
        console.log(`尝试重连第${this.reconnectCount}次`);
        
        this.reconnectTimer = setTimeout(() => {
          this.connectWebSocket();
        }, 3000 * this.reconnectCount);
      }
    },
    
    // 关闭WebSocket连接
    closeWebSocket() {
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
      }
      
      if (this.socketTask) {
        this.socketTask.close();
        this.socketTask = null;
      }
    },

    // 加载消息列表
    loadMessageList() {
      if (this.loading || !this.hasMore) return;
      
      this.loading = true;

      this.$api.req(`/promotion/kefu-message/page`, {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        opsUserId: -1
      }, 'GET', 'JSON', false)
        .then(res => {
          if (res.code === 0 && res.data) {
            const newMessages = res.data.list.map((msg, index) => ({
              id: msg.id || Date.now() + index,
              content: this.parseContent(msg.content),
              userType: msg.senderType === 1 ? 'self' : 'friend',
              avatar: msg.senderType === 1 ? (this.userInfo.avatar || '/static/img/tabs/my.png') : this.friendAvatar,
              createTime: msg.createTime,
              showTime: false
            }));

            if (this.currentPage === 1) {
              this.messageList = newMessages.reverse();
              this.recomputeShowTime();
              this.scrollToBottom();
            } else {
              this.messageList = [...newMessages.reverse(), ...this.messageList];
              this.recomputeShowTime();
            }

            this.total = res.data.total;
            this.hasMore = this.messageList.length < this.total;
          }
        })
        .catch(err => {
          console.error('加载消息失败:', err);
          uni.showToast({
            title: '加载消息失败',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 发送消息
    sendMessage() {
      const nowTs = Date.now();
      if (nowTs - this.lastSendAt < 400) return;
      this.lastSendAt = nowTs;
      
      const messageContent = this.inputText.trim();
      if (!messageContent || this.sendingInProgress) return;
      
      this.inputText = '';
      
      // 先添加到本地消息列表
      const tempMessage = {
        id: 'temp_' + Date.now(),
        content: messageContent,
        userType: 'self',
        avatar: this.userInfo.avatar || '/static/img/tabs/my.png',
        createTime: Date.now(),
        showTime: (this.messageList.length === 0) ? true : this.shouldShowTime(Date.now(), this.messageList[this.messageList.length - 1].createTime),
        isSending: true,
        isRead: false,
        isFailed: false
      };
      
      this.addMessage(tempMessage);
      
      // 发送到服务器
      this.sendingInProgress = true;
      this.$api.req('/promotion/kefu-message/send', {
        contentType: 1,
        content: messageContent,
        opsUserId: -1
      }, 'POST', 'JSON', false)
      .then(res => {
        if (res.code === 0) {
          this.updateMessageStatus(tempMessage.id, false);
          this.refreshMessageList();
        } else {
          throw new Error(res.msg || '发送失败');
        }
      })
      .catch(err => {
        console.error('发送消息失败:', err);
        this.updateMessageStatus(tempMessage.id, false, true);
        uni.showToast({
          title: '发送失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.sendingInProgress = false;
        setTimeout(() => {
          this.inputFocus = true;
        }, 100);
      });
    },
    
    // 添加消息到列表
    addMessage(message) {
      this.messageList.push(message);
      if (this.isAtBottom || message.userType === 'self') {
        this.scrollToBottom(message);
        this.showNewMsgTip = false;
        this.unreadCount = 0;
      } else {
        this.showNewMsgTip = true;
        this.unreadCount += 1;
      }
      
      setTimeout(() => {
        if (this.isAtBottom || message.userType === 'self') {
          this.scrollToBottom(message);
        }
      }, 200);
    },
    
    // 更新消息状态
    updateMessageStatus(messageId, isSending, isFailed = false) {
      const message = this.messageList.find(msg => msg.id === messageId);
      if (message) {
        message.isSending = isSending;
        message.isFailed = isFailed;
      }
    },
    
    // 刷新消息列表
    refreshMessageList() {
      this.currentPage = 1;
      this.hasMore = true;
      this.loadMessageList();
    },

    // 滚动到消息底部
    scrollToBottom(message) {
      this.$nextTick(() => {
        if (message && (message.id || message.tempId)) {
          this.lastMessageAnchor = 'msg-' + (message.id || message.tempId);
        } else if (this.messageList.length) {
          const last = this.messageList[this.messageList.length - 1];
          this.lastMessageAnchor = 'msg-' + (last.id || (this.messageList.length - 1));
        }
        this.isAtBottom = true;
        this.showNewMsgTip = false;
        this.unreadCount = 0;
      });
    },

    // 监听滚动
    onScroll(e) {
      try {
        const top = e.detail.scrollTop || 0;
        const sh = e.detail.scrollHeight || 0;
        const ch = e.detail.clientHeight || e.detail.height || 0;
        if (sh && ch) {
          this.isAtBottom = (sh - ch - top) < 60;
          if (this.isAtBottom) {
            this.showNewMsgTip = false;
            this.unreadCount = 0;
          }
        }
      } catch (err) {}
    },

    // 加载更多消息
    loadMoreMessages() {
      const now = Date.now();
      if (!this._lastMoreTs) this._lastMoreTs = 0;
      if (now - this._lastMoreTs < 500) return;
      if (!this.loading && this.hasMore) {
        this._lastMoreTs = now;
        this.currentPage += 1;
        this.loadMessageList();
      }
    },
    
    // 判断是否显示时间
    shouldShowTime(currentTs, prevTs = null) {
      if (!prevTs) return true;
      const cur = Number(currentTs);
      const prev = Number(prevTs);
      if (!isFinite(cur) || !isFinite(prev)) return true;
      const curD = new Date(cur);
      const prevD = new Date(prev);
      const isSameDay = curD.getFullYear() === prevD.getFullYear() && curD.getMonth() === prevD.getMonth() && curD.getDate() === prevD.getDate();
      if (!isSameDay) return true;
      return (cur - prev) > 5 * 60 * 1000;
    },

    // 统一为当前列表计算 showTime
    recomputeShowTime() {
      let prevTs = null;
      for (let i = 0; i < this.messageList.length; i++) {
        const m = this.messageList[i];
        const show = this.shouldShowTime(m.createTime, prevTs);
        this.$set(this.messageList[i], 'showTime', show);
        prevTs = m.createTime;
      }
    },

    // 格式化时间显示
    formatTime(timestamp) {
      const now = new Date();
      const messageTime = new Date(timestamp);
      const diff = now.getTime() - messageTime.getTime();
      
      if (diff < 24 * 60 * 60 * 1000 && messageTime.getDate() === now.getDate()) {
        return messageTime.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (messageTime.getDate() === yesterday.getDate()) {
        return '昨天 ' + messageTime.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      return messageTime.toLocaleString('zh-CN', { 
        year: 'numeric',
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit', 
        minute: '2-digit'
      });
    },
    
    // 输入框焦点事件
    onInputFocus() {
      this.inputFocus = true;
      setTimeout(() => {
        this.scrollToBottom();
      }, 500);
    },
    
    onInputBlur() {
      // 保持输入框焦点
    },
    
    // 长按消息操作
    onMessageAction(message) {
      const itemList = [];
      if (message && message.content) itemList.push('复制');
      if (message && message.userType === 'self') itemList.push('删除');
      if (!itemList.length) return;
      
      uni.showActionSheet({
        itemList,
        success: (res) => {
          const choice = itemList[res.tapIndex];
          if (choice === '复制') {
            uni.setClipboardData({ data: message.content });
          } else if (choice === '删除') {
            this.messageList = this.messageList.filter(m => m.id !== message.id);
          }
        }
      });
    },
    
    // 聚焦输入框
    focusInput() {
      this.inputFocus = true;
    },
    
    // 切换表情面板
    toggleEmojiPanel() {
      this.showEmojiPanel = !this.showEmojiPanel;
      if (this.showEmojiPanel) {
        this.inputFocus = false;
      } else {
        setTimeout(() => {
          this.inputFocus = true;
        }, 100);
      }
    },
    
    // 关闭表情面板
    closeEmojiPanel() {
      this.showEmojiPanel = false;
      setTimeout(() => {
        this.inputFocus = true;
      }, 100);
    },
    
    // 选择表情
    selectEmoji(emoji) {
      this.inputText += emoji;
      this.showEmojiPanel = false;
      setTimeout(() => {
        this.inputFocus = true;
      }, 200);
    },
    
    // 显示更多选项
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['清空聊天记录', '举报'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 清空聊天记录
            uni.showModal({
              title: '确认清空',
              content: '确定要清空所有聊天记录吗？',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  this.messageList = [];
                }
              }
            });
          } else if (res.tapIndex === 1) {
            // 举报
            uni.showToast({
              title: '举报功能待实现',
              icon: 'none'
            });
          }
        }
      });
    },
    
    // 解析消息内容
    parseContent(raw) {
      try {
        if (raw == null) return '';
        if (typeof raw === 'string') {
          const s = raw.trim();
          if (s.startsWith('{') && s.endsWith('}')) {
            const obj = JSON.parse(s);
            if (obj && typeof obj === 'object') {
              if (obj.text) return String(obj.text).replace(/\n/g, '\n');
              if (obj.content) return String(obj.content).replace(/\n/g, '\n');
            }
          }
          return s;
        }
        if (typeof raw === 'object') {
          if (raw.text) return String(raw.text);
          if (raw.content) return String(raw.content);
          return JSON.stringify(raw);
        }
        return String(raw);
      } catch (e) {
        return String(raw);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
}

/* 聊天头部 */
.chat-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  z-index: 100;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .header-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    border: 3rpx solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  }

  .header-info {
    display: flex;
    flex-direction: column;
  }

  .friend-name {
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 8rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  }

  .online-status {
    font-size: 24rpx;
    opacity: 0.8;
    
    &.online {
      color: #4CAF50;
    }
    
    &:not(.online) {
      color: #ff9800;
    }
  }

  .header-right {
    padding: 10rpx;
  }
}

/* 消息列表 */
.message-list {
  position: fixed;
  top: 120rpx;
  left: 0;
  right: 0;
  bottom: 120rpx;
  background: #f5f5f5;
}

.message-container {
  padding: 20rpx 30rpx 200rpx;
  min-height: 100%;
}

.new-msg-tip {
  position: fixed;
  right: 20rpx;
  bottom: 140rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
  padding: 12rpx 20rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.12);
  z-index: 130;
}

/* 加载更多 */
.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .load-text {
    margin-left: 10rpx;
    font-size: 24rpx;
    color: #999;
  }
}

/* 消息项 */
.message-item {
  margin-bottom: 30rpx;

  &.show-time {
    .message-time {
      display: block;
    }
  }

  .message-time {
    display: none;
    text-align: center;
    font-size: 22rpx;
    color: #9aa0a6;
    margin-bottom: 20rpx;
    padding: 8rpx 16rpx;
    background: rgba(0, 0, 0, 0.06);
    border-radius: 24rpx;
    margin-left: auto;
    margin-right: auto;
    width: fit-content;
  }

  .message-content {
    display: flex;
    align-items: flex-end;
    max-width: 100%;

    &.self {
      flex-direction: row-reverse;
    }
  }

  .message-avatar {
    width: 64rpx;
    height: 64rpx;
    border-radius: 50%;
    margin: 0 16rpx;
    flex-shrink: 0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }

  .text-avatar {
    background: linear-gradient(135deg, #8ec5fc 0%, #e0c3fc 100%);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: 600;
  }

  .message-bubble {
    max-width: 60%;
    padding: 16rpx 20rpx;
    border-radius: 20rpx;
    position: relative;
    word-wrap: break-word;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.08);

    &.self {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-bottom-right-radius: 8rpx;

      &::after {
        content: '';
        position: absolute;
        right: -8rpx;
        bottom: 8rpx;
        width: 0;
        height: 0;
        border: 8rpx solid transparent;
        border-left-color: #667eea;
      }
    }

    &.friend {
      background: #fff;
      color: #333;
      border: 1rpx solid #eaeaea;
      border-bottom-left-radius: 8rpx;

      &::after {
        content: '';
        position: absolute;
        left: -8rpx;
        bottom: 8rpx;
        width: 0;
        height: 0;
        border: 8rpx solid transparent;
        border-right-color: #fff;
      }
    }
  }

  .message-text {
    font-size: 28rpx;
    line-height: 1.4;
    word-break: break-all;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .empty-icon {
    font-size: 120rpx;
    margin-bottom: 30rpx;
    opacity: 0.5;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 输入区域 */
.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-top: 1rpx solid #ececec;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  z-index: 100;
}

.input-container {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 28rpx;
  padding: 10rpx 20rpx;
  border: 1rpx solid #e6e6e6;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.emoji-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
  transition: all 0.3s ease;

  &:active {
    background: rgba(102, 126, 234, 0.1);
    transform: scale(0.95);
  }

  &.active {
    background: rgba(102, 126, 234, 0.1);
    color: #667eea;
  }
}

.emoji-icon {
  font-size: 24rpx;
  line-height: 1;
}

.message-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  background: transparent;
  border: none;
  outline: none;
  padding: 0 20rpx;
}

.send-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #bfbfbf;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &.active {
    background: linear-gradient(135deg, #667eea, #764ba2);
    transform: scale(1.05);
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  }
}

/* 表情面板 */
.emoji-panel {
  position: absolute;
  bottom: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1rpx solid #e5e5e5;
  border-radius: 20rpx 20rpx 0 0;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 200;
  max-height: 400rpx;
  transform: translateY(100%);
  opacity: 0;
  transition: all 0.3s ease;

  &.show {
    transform: translateY(0);
    opacity: 1;
  }
}

.emoji-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.emoji-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.emoji-close {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  transition: all 0.3s ease;

  &:active {
    background: #e5e5e5;
    transform: scale(0.95);
  }
}

.emoji-list {
  height: 300rpx;
  padding: 20rpx;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8rpx;
  padding: 10rpx 0;
}

.emoji-item {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  border-radius: 8rpx;
  transition: all 0.2s ease;
  background: transparent;
  margin: 0 auto;

  &:active {
    background: #e3f2fd;
    transform: scale(0.85);
  }
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .message-bubble {
    max-width: 80%;
  }
}
</style>
